import { PageContainer } from '@ant-design/pro-layout';
import { Button, message, Popconfirm, Form } from 'antd';
import ProTable from '@ant-design/pro-table';
import ProForm, { DrawerForm, ProFormRadio, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import React, { useState, useRef } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { PlusOutlined } from '@ant-design/icons';
import { Customer, TreeData } from '../../../model';
import { Cascader } from 'antd';
import { customerList, areaTwo, deleteCustomer, saveCustomer, updateCustomer } from '../service';
import CustomerAuth from '@/components/Common/CustomerAuth';

export default (() => {
  const [showCreate, setShowCreate] = useState(false);
  const [editModel, setEditModel] = useState<Customer>();
  const [areas, setAreas] = useState<TreeData[]>();
  const [fullArea, setFullArea] = useState<string[]>();
  const actionRef = useRef<ActionType>();
  const authRef = useRef();

  async function requestAreas() {
    var val = await areaTwo();
    setAreas(val.data);
  }

  React.useEffect(() => {
    requestAreas();
    return function cleanup() {};
  }, []);

  const handleDelete = async (id: string) => {
    var val = await deleteCustomer({
      ids: id
    });

    if (val.errorCode === '200') {
      message.success('删除成功');
      actionRef.current?.reloadAndRest?.();
    } else {
      message.error(val.errorMessage);
    }
  }; //表头信息以及表值设置


  const columns: ProColumns<Customer>[] = [{
    title: '客户代码',
    dataIndex: 'bh'
  }, {
    title: '客户名称',
    dataIndex: 'name'
  }, {
    title: '客户类型',
    dataIndex: 'customerType',
    valueType: 'select',
    valueEnum: {
      1: {
        text: '二级客户'
      },
      2: {
        text: '医院托管'
      },
      3: {
        text: '临时客户'
      },
      0:{
        text: '其他'
      }
    }
  }, {
    title: '地区',
    dataIndex: 'city',
    valueType: 'select',
    hideInSearch: true,
    renderText: (_, record: any) => `${record.provinces_label}/${record.city_label}`
  }, {
    title: '地址',
    dataIndex: 'address',
    hideInSearch: true
  }, {
    title: '操作',
    valueType: 'option',
    // hideInTable: sessionStorage.getItem('access')!='admin',
    render: (text, record:any, _, action) => [<a key='dealer' onClick={async () => {
      authRef.current.showAuth(record.id);
    }}>授权</a>, <a key='editable' onClick={() => {
      record.areas = [record.provinces, record.city];
      setFullArea([record.provinces_label, record.city_label]);
      setEditModel(record);
      setShowCreate(true);
    }}>
          编辑
        </a>, <Popconfirm title='确定删除该客户吗?' key='delete' onConfirm={() => handleDelete(record.id)}>
          <a>删除</a>
        </Popconfirm>]
  }];

  function onChange(info, label) {
    if (label.length > 1) {
      setFullArea([label[0].label, label[1].label]);
    } else {
      setFullArea([label[0].label]);
    }
  }

  const formRef = useRef();
  return <PageContainer>
    <ProTable<Customer> scroll={{x:1200}} actionRef={actionRef} headerTitle='客户列表' request={async (params, sorter, filter) => customerList({ ...params,
      filter
    })} columns={columns} rowKey='id' search={{
      labelWidth: 120
    }} pagination={{
      pageSizeOptions: ['20', '100', '500']
    }} toolBarRender={() => [<Button type='primary' key='primary' // hidden={sessionStorage.getItem('access')!='admin'}
    onClick={() => {
      setEditModel(undefined);
      setShowCreate(true);
    }} >
          <PlusOutlined/>新建
    </Button>]} toolbar={{
      settings: []
    }} pagination={{
      pageSizeOptions: ['20', '100', '500']
    }} />
         <DrawerForm title={editModel ? '客户编辑' : '客户新增'} onVisibleChange={setShowCreate} visible={showCreate} formRef={formRef} drawerProps={{
      forceRender: true,
      destroyOnClose: true
    }} onFinish={async (values: any) => {
      var val;
      values.provinces_label = fullArea?.[0];
      values.city_label = fullArea?.[1];
      values.provinces = values.areas?.[0];
      values.city = values.areas?.[1];

      if (editModel) {
        values.id = editModel.id;
        val = await updateCustomer(values);
      } else {
        val = await saveCustomer(values);
      }

      if (val.errorCode === '200') {
        message.success('提交成功');
        actionRef.current?.reloadAndRest?.();
        return true;
      } else {
        message.error(val.errorMessage);
        return false;
      }
    }}>
           <ProForm.Group>
              <ProFormText name='name' label='签约客户名称(中文)'  placeholder='请输入客户中文名称' width='md' initialValue={editModel?.name} rules={[{
          required: true
        }]} />
              <ProFormText name='cusENName' label='客户名称(英文)' placeholder='请输入客户英文名称' width='md' initialValue={editModel?.cusENName} />
           </ProForm.Group>
            <ProForm.Group >
              <ProFormText name='phone' label='电话' placeholder='请输入客户电话' width='md' initialValue={editModel?.phone} rules={[{required: true}]}  />
              <ProFormText name='zipCode' label='邮政编码' placeholder='请输入邮政编码' initialValue={editModel?.zipCode} width='md' />
              <ProFormRadio.Group name='customerType' rules={[{required: true}]} label='商业客户类型' initialValue={editModel?.customerType} options={[{
          label: '二级客户',
          value: 1
        }, {
          label: '医院托管',
          value: 2
        }, {
          label: '临时客户',
          value: 3
        },{
          label: '其他',
          value: 0
        }]}  />
          </ProForm.Group>
          <Form.Item style={{
        width: '330px'
      }} initialValue={editModel?.areas} name='areas' label='地区' rules={[{
        required: true
      }]} >
              <Cascader options={areas} placeholder='请选择' onChange={onChange} />
          </Form.Item>
          <ProFormText name='address' label='详细地址' placeholder='请输入地址' width='lg' initialValue={editModel?.address}/>
          <ProFormTextArea name='remarks' label='备注' placeholder='请输入备注' initialValue={editModel?.remarks} fieldProps={{
        showCount: true,
        maxLength: 200
      }}>
          </ProFormTextArea>
          {
        /* <ProFormTextArea name=mails label=通知邮箱 placeholder=请输入通知邮箱，多个邮箱用,隔开  initialValue={jhuang@strokemedical.com,jycong@strokemedical.com,chenbingbing_123@163.com}>
        </ProFormTextArea> */
      }
         </DrawerForm>
         <CustomerAuth ref={authRef} />
  </PageContainer>;
});